package com.xiao.androidcompose01.viewmodel

import cafe.adriel.voyager.core.model.StateScreenModel
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.map.geolocation.TencentLocationRequest
import com.tencent.trtc.TRTCCloud
import com.tencent.trtc.TRTCCloudListener
import com.xiao.androidcompose01.api.data.AccountData
import org.koin.core.annotation.Factory
import org.koin.core.annotation.Module

@Module
@Factory
class TencentMapModel (private val cloud: TRTCCloud) : StateScreenModel<TencentMapModel.TencentMapState>(TencentMapState.Idle),TencentLocationListener {
   sealed class TencentMapState{
      data object Idle: TencentMapState()
   }
   
   private val listener = object : TRTCCloudListener() {
      override fun onRecvCustomCmdMsg(userId: String?, cmdID: Int, seq: Int, message: ByteArray?) {
         super.onRecvCustomCmdMsg(userId, cmdID, seq, message)
      }
   }
   
   private var cacheAccountData: AccountData? = null
   fun startLocation(accountData: AccountData){
      cloud.addListener(listener)
      cacheAccountData = accountData
      if (!accountData.isParent()){ //只有子端才能够进行
         val request = TencentLocationRequest.create()
         TencentLocationManager.getInstance().requestLocationUpdates(request,this,0)
      }
   }
   
   private fun sendLocation(latitude: Double,longitude: Double,address: String,time: Long){
      TencentMsgUtils.sendLocation(cloud,latitude,longitude,address,time)
   }
   
   override fun onLocationChanged(
      location: TencentLocation?,
      code: Int,
      msg: String?
   ) {
      if (code==0 && location!=null){
         sendLocation(location.latitude,location.longitude,location.address,location.time)
      }
   }
   
   override fun onStatusUpdate(p0: String?, p1: Int, p2: String?) {
   }
   
   override fun onGnssInfoChanged(p0: Any?) {
   }
   
   override fun onNmeaMsgChanged(p0: String?) {
   }
}